package com.aq.appserver.server.user.service.impl;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.aq.appserver.server.user.bean.UserBean;
import com.aq.appserver.server.user.dao.UserDao;
import com.aq.appserver.server.user.entity.User;
import com.aq.appserver.server.user.service.UserService;

@Service
public class UserServiceImpl implements UserService {

	@Autowired
	private UserDao userDao;
	
	@Transactional
	@Override
	public void delete(UserBean user) {
		String[] ids = user.getUserID().split(",");
		for(int i=0; i<ids.length; i++)
		{
			userDao.delete(Long.parseLong(ids[i]));
		}
	}

	@Override
	public List<User> queryAll() {
		Iterable<User> it = userDao.findAll();
		List<User> list = new ArrayList<User>();
		Iterator<User> itr = it.iterator();
		while(itr.hasNext())
		{
			list.add(itr.next());
		}
		return list;
	}

	@Override
	public void save(User user) {
		// TODO Auto-generated method stub
		userDao.save(user);
	}

	@Override
	public void update(User user) {
		// TODO Auto-generated method stub
		//userDao.updateUser(user.getId(), user.getUserName(), user.getUserCode(), user.getPassword());
	}

	@Override
	public void validateLogin(UserBean userBean, Map<String, Object> result, HttpServletRequest request) {
		if(!userBean.getVeryCode().equals((String)request.getSession().getAttribute("validateCode")))
		{
			result.put("flag", "1");
			result.put("msg", "验证码错误");
			return;
		}
		
		User usr = userDao.findByUserName(userBean.getUserName());
		if(usr==null)
		{
			result.put("flag", "2");
			result.put("msg", "用户不存在");
			return;
		}
		
		if(!usr.getPassword().equals(userBean.getPassword()))
		{
			result.put("flag", "3");
			result.put("msg", "密码不正确");
			return;
		}
		
		result.put("flag", "0");
		result.put("msg", "success");
	}

}
